Maximum depth of binary tree¶
Time: O(N); Space: O(H); easy
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example 1:
Input: root = {TreeNode} [3,9,20,None,None,15,7]
3
/ \
9 20
/ \
15 7
Output: 3
[1]:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution1(object):
"""
Time: O(N)
Space: O(H), H is height of Binary Tree
"""
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: integer
"""
if root is None:
return 0
else:
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
[3]:
s = Solution1()
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
assert s.maxDepth(root) == 3